{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        encoder_out, encoder_state = tf.nn.dynamic_rnn(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "            inputs = tf.nn.embedding_lookup(embeddings, self.X),\n",
    "            sequence_length = self.X_seq_len,\n",
    "            dtype = tf.float32)\n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-61798a68b45e>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-61798a68b45e>:33: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-61798a68b45e>:36: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[25507, 30476, 30476, 30476, 30288, 30288, 30288,  6869,  4344,\n",
       "          4344,  4344,  4727,  4344, 19329, 19329, 19329, 19329, 11026,\n",
       "         16153, 16153, 16153, 16153, 16153, 16153, 18614, 13763,   925,\n",
       "         31739,   925,  1883,  1883,  1883,  1883,  1883,  1883,  1883,\n",
       "         28615, 28615, 13490, 13490, 13490, 13490, 13490, 13490, 13490,\n",
       "         15782, 15782, 15782, 15782, 28372, 27509, 28372, 28372, 28372,\n",
       "         21754, 21754, 21754, 21754, 21754,  9832,  9832,  9832,  7652,\n",
       "          7652,  7652,  7652,  7652,  7652, 27509, 27509, 27509, 27509],\n",
       "        [ 5499, 12746, 12746, 15702, 15702, 15702, 15702, 15702, 17510,\n",
       "          7832,  7832,  7832,  7832,  7832,  7832,  7832,  7832,  7832,\n",
       "          7832,  7832, 21267, 14591, 14591, 21267, 21267, 21267, 10229,\n",
       "         10229, 10229, 10229, 10229, 10229, 23192, 23192, 23192, 23192,\n",
       "         25841, 25841, 10491, 10491, 18560, 18560, 18560, 18294, 18294,\n",
       "         18294, 18294, 18294, 17616, 17616, 17616, 17616, 17616, 30115,\n",
       "         30115, 30115, 30115,  7368,  7368,  7368,  7368,  7368, 12847,\n",
       "         12847, 12847, 12847, 12847, 12847, 27928, 27928, 27928, 21558],\n",
       "        [17726, 10466, 10466, 28474, 10466, 16859, 16859, 16859, 16859,\n",
       "         16859, 18561, 18561, 22063,  4918,  4733,  4733,  4733, 12195,\n",
       "         12195, 12195, 12195, 12195, 12195, 23903, 23903, 23903, 23903,\n",
       "         23903, 23903, 23903, 23903, 27029, 27439, 27439, 27439, 27439,\n",
       "          6138, 12025,  3911,  3911,  3911,  3911,  3911,  3911,  3911,\n",
       "         26278,  9810,  9810,  9810,  9810,  9810,  9810,  5301,  2112,\n",
       "          2112,  2112, 21743, 12829, 12829, 12829, 21743, 21883,  6157,\n",
       "          6157,  6157,  6157,  6157,  6157,   174,   174, 18946, 18946],\n",
       "        [10154,  7030, 23375, 23375, 23375, 23375,   550, 17904,   550,\n",
       "         17904,   126,   126,   126,   126,   126,   126,   126,   126,\n",
       "           126,   126, 18880, 18880,   126, 18880, 18880, 18880, 18880,\n",
       "         18880, 18880,  5265,  5265,  5265,  5265,  5265,  5265, 10306,\n",
       "         10306, 10306, 10306, 10306, 10306,  1198,  1198,  1198, 24348,\n",
       "         24348, 24348, 24348,  1198,  1198, 29578, 29578, 29578, 29578,\n",
       "         27378, 27378, 27378,  5547,  5547,  5547,  5547, 11497, 31810,\n",
       "         11497, 11497, 11497, 11497, 11497, 12495, 12495, 12495,  9695],\n",
       "        [ 9805,  4610, 23317, 17865, 17865,  6578,  1495,  1495,  5517,\n",
       "          5517,  5517,  5517,  5517,  5517,  5517, 31549, 31549, 22771,\n",
       "          4559, 21709, 21709, 17404, 17404, 17404, 17404, 17404, 17404,\n",
       "         28291, 28291, 28291, 28291, 28291, 28291, 28291, 28291, 28291,\n",
       "         28291, 30726, 30726, 25989, 30726, 25989, 25989, 25989, 25989,\n",
       "         25989,  1740,  1740,  1740, 26721, 27053, 27053, 24830, 24830,\n",
       "         24830, 24830, 24830, 24830, 24830, 24830, 24830, 24830, 24830,\n",
       "         24830, 10525, 24830, 10525, 10525, 15722, 15722, 14012, 14012],\n",
       "        [15479, 13567, 13567, 31284, 31284,  2858,  2858,  2760,  2760,\n",
       "          2760,  2760,  2760, 31123, 19975, 27237, 19975, 19975, 31802,\n",
       "         31802, 31802, 16222, 15348, 15348, 31428, 31428, 31428, 28831,\n",
       "         28831, 28831, 10491, 10491, 10491, 13895, 13895, 13895, 13895,\n",
       "         13895, 13895, 13895,  6564,  6564,  6564, 27536, 27536,  8195,\n",
       "          8195,  8195, 19396, 19396,  2576, 19396, 13895, 13895, 13895,\n",
       "         13895, 13895, 16828, 16828, 16828, 16828, 16828, 16828, 16828,\n",
       "         16828, 18408, 24983, 24983, 24983, 11617, 11617, 11617, 11617],\n",
       "        [ 1827, 17229, 28553, 31602, 31602, 31602,  6092, 21424, 21424,\n",
       "          5305,  5305,  5305,  5305, 16957, 16957, 16957, 16957, 16957,\n",
       "         16957, 16957,   173, 18141, 29222, 29222, 29222, 29222, 29222,\n",
       "         10019, 10019, 29222, 10019, 10019, 10019, 10019, 29791, 29791,\n",
       "         29791, 29791, 29791, 14038, 14038, 14038, 14038, 14038,  3374,\n",
       "          3374, 31124,  3158,  3158,  3158,  3158,  3158,  3158,  3158,\n",
       "          3158,  3158,  3158,  3158,  3158,  3158,  3158,  3158,  3158,\n",
       "          3158,  3158,  3158,  3158,  3158,  3158,  3158,  2170,  2170],\n",
       "        [ 2842, 18022, 18022, 24660, 12311, 12311, 12311, 12311, 12311,\n",
       "         12311,  9639,  9639,  9639,  9639,  9639,  9639,  9639, 31310,\n",
       "         31310, 31310, 31310, 18486, 15688, 18486, 14685, 16640, 16640,\n",
       "         16640, 16640, 16640, 16640, 27350, 27350, 27350, 25351,  9870,\n",
       "         14785, 14785, 31936,  7565,  7565,  7565,  7565,  7565,  3159,\n",
       "         28376,  3159, 28376,  3159,  4889,  4889,  4889,  3159,  3159,\n",
       "          3159,  3159, 31306, 31306, 31306, 31306, 31306, 31306, 31306,\n",
       "         31306, 23673, 15212, 15212, 15212, 15212, 15212, 16319, 16319],\n",
       "        [ 4721,  4721, 24020, 24020,  4028,  4028,  4028, 14951, 31330,\n",
       "         31330, 31330, 31330, 31330, 31330, 31330,  7368,  7368,  7368,\n",
       "          7368,  7368, 19614, 19614, 19614, 10639, 10639, 10639, 10639,\n",
       "         10639,  7265,  7265,  7265,  7265,  7265,  7265,  7265,  7265,\n",
       "          7265,  7265,  7265, 13824,  7265, 13824, 13824, 13824, 13824,\n",
       "         13824,  7516,  7516,  7516,  7516, 26307, 26307, 19590, 19590,\n",
       "         19590, 19590, 19590, 19590, 18522, 18522, 20312, 20312, 20312,\n",
       "         20312, 20312, 20312, 20312, 20312,  4648, 18052, 15308, 15308],\n",
       "        [10068,  6869,  6869, 12858, 12858, 12858, 12858, 14428, 14428,\n",
       "         31281, 24315, 24315, 24315, 24315, 24315, 21409, 24315, 14527,\n",
       "         12709, 12709, 12709, 12709, 12709, 12709, 16728, 21356, 17562,\n",
       "         17562, 17562,  4504, 13629, 13629, 13629,   190,   190,   190,\n",
       "         13920, 29885, 29885,  7328,  7328,  7328,  7328,  7328, 17919,\n",
       "         17919, 17919, 17919, 17919, 24855, 24855, 24855, 24855, 20240,\n",
       "         20240, 20240, 20240, 22604, 22604, 22604, 22604,  3822, 15200,\n",
       "         15200,  3425,  3425, 28879, 28879, 28879, 13411, 13411, 13411]],\n",
       "       dtype=int32), 10.372644, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:06<00:00,  2.34it/s, accuracy=0.383, cost=3.71]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.87it/s, accuracy=0.419, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 4.984682, training avg acc 0.262190\n",
      "epoch 1, testing avg loss 3.598807, testing avg acc 0.390468\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.49, cost=2.76] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.446, cost=2.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 3.156605, training avg acc 0.439214\n",
      "epoch 2, testing avg loss 3.080271, testing avg acc 0.451487\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.567, cost=2.2] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.489, cost=2.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 2.621073, training avg acc 0.501004\n",
      "epoch 3, testing avg loss 2.908529, testing avg acc 0.472729\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.613, cost=1.84]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.511, cost=2.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 2.301177, training avg acc 0.541241\n",
      "epoch 4, testing avg loss 2.820460, testing avg acc 0.486535\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.651, cost=1.6] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.527, cost=2.57]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 2.089698, training avg acc 0.569203\n",
      "epoch 5, testing avg loss 2.832526, testing avg acc 0.492157\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.678, cost=1.41]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.565, cost=2.56]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 1.916657, training avg acc 0.593127\n",
      "epoch 6, testing avg loss 2.876892, testing avg acc 0.493310\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.699, cost=1.28]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.532, cost=2.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 1.787738, training avg acc 0.611230\n",
      "epoch 7, testing avg loss 2.933894, testing avg acc 0.489890\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.71, cost=1.24] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.516, cost=2.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 1.690416, training avg acc 0.624981\n",
      "epoch 8, testing avg loss 3.035955, testing avg acc 0.484817\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.723, cost=1.12]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.505, cost=2.83]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 1.609456, training avg acc 0.636603\n",
      "epoch 9, testing avg loss 3.122440, testing avg acc 0.480258\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.739, cost=1.03]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.516, cost=2.88]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 1.519837, training avg acc 0.650704\n",
      "epoch 10, testing avg loss 3.157265, testing avg acc 0.486440\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.757, cost=0.952]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.92it/s, accuracy=0.543, cost=2.87]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 1.479938, training avg acc 0.655967\n",
      "epoch 11, testing avg loss 3.203252, testing avg acc 0.483667\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:18<00:00,  2.30it/s, accuracy=0.77, cost=0.897]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.5, cost=3]     \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 1.426198, training avg acc 0.664423\n",
      "epoch 12, testing avg loss 3.266869, testing avg acc 0.482668\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.758, cost=0.876]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.90it/s, accuracy=0.522, cost=3.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 1.392510, training avg acc 0.669664\n",
      "epoch 13, testing avg loss 3.333741, testing avg acc 0.483009\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.769, cost=0.869]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.511, cost=3.02]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 1.403040, training avg acc 0.666338\n",
      "epoch 14, testing avg loss 3.392766, testing avg acc 0.483389\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.784, cost=0.826]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.94it/s, accuracy=0.511, cost=3.28]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 1.300561, training avg acc 0.686010\n",
      "epoch 15, testing avg loss 3.460643, testing avg acc 0.480245\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.775, cost=0.818]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.93it/s, accuracy=0.538, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 1.280744, training avg acc 0.688406\n",
      "epoch 16, testing avg loss 3.557242, testing avg acc 0.471351\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.796, cost=0.81]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.89it/s, accuracy=0.538, cost=3.04]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 1.286736, training avg acc 0.685862\n",
      "epoch 17, testing avg loss 3.566288, testing avg acc 0.469775\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.79, cost=0.791]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.95it/s, accuracy=0.548, cost=3.1] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.250707, training avg acc 0.692633\n",
      "epoch 18, testing avg loss 3.573932, testing avg acc 0.475422\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:19<00:00,  2.30it/s, accuracy=0.783, cost=0.799]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.91it/s, accuracy=0.5, cost=3.36]  \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 1.235801, training avg acc 0.694855\n",
      "epoch 19, testing avg loss 3.626958, testing avg acc 0.477027\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [11:17<00:00,  2.31it/s, accuracy=0.791, cost=0.739]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:08<00:00,  4.97it/s, accuracy=0.489, cost=3.39]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.205937, training avg acc 0.700262\n",
      "epoch 20, testing avg loss 3.676048, testing avg acc 0.476159\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:29<00:00,  1.36it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.1767827"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
